package com.dragon.framework.json.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import jakarta.servlet.ServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * ServletResponse序列化
 *
 * @author dragon
 * @version 1.0
 * @date 2024/10/12 10:25
 */
public class ServletResponseSerializer extends JsonSerializer<ServletResponse> {

    Logger log = LoggerFactory.getLogger(ServletResponseSerializer.class);


    /**
     * Method that can be called to ask implementation to serialize
     * values of type this serializer handles.
     *
     * @param value       Value to serialize; can <b>not</b> be null.
     * @param gen         Generator used to output resulting Json content
     * @param serializers Provider that can be used to get serializers for
     *                    serializing Objects value contains, if any.
     */
    @Override
    public void serialize(ServletResponse value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (value != null) {
            try {
                // 增加对ToStringSerializer.instance.valueToString()方法内部可能抛出的异常的处理
                String valueAsString = ToStringSerializer.instance.valueToString(value);
                // 假设已知valueAsString不为null，因ToStringSerializer的实现未知，此处不作额外空检查
                gen.writeString(valueAsString);
            } catch (Exception e) {
                // 根据具体情况，可以选择记录日志、抛出自定义异常或忽略
                // 此处示例为打印堆栈信息，实际应用中可能需要更细致的异常处理策略
                log.error("ServletResponse序列化异常 {}", e.getMessage(), e);
                // 根据需要考虑是否需要继续抛出异常或者处理异常保证程序继续运行
            }
        }
    }

}
